package com.dragon.logical.service.supplies.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dragon.common.model.ResultCode;
import com.dragon.common.model.exception.CustomException;
import com.dragon.common.util.DateNumUtils;
import com.dragon.repository.entity.*;
import com.dragon.repository.mapper.*;
import com.dragon.logical.service.supplies.IWarehouseInoutService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 出入库 服务实现类
 * </p>
 *
 * @author sy
 * @since 2023-11-14
 */
@Service
public class WarehouseInoutServiceImpl extends ServiceImpl<WarehouseInoutMapper, WarehouseInout> implements IWarehouseInoutService {

    @Autowired
    WarehouseInoutMapper inoutMapper;
    @Autowired
    StockMapper stockMapper;
    @Autowired
    InoutProductMapper inoutProductMapper;
    @Autowired
    WarehouseMapper warehouseMapper;
    @Autowired
    AdminMapper adminMapper;
    @Autowired
    DepartmentMapper departmentMapper;
//    @Autowired
//    AllocateMapper allocateMapper;
//    @Autowired
//    AllocateProductMapper allocateProductMapper;
//    @Autowired
//    WarehouseClaimMapper claimMapper;
    @Autowired
    ProductMapper productMapper;
//    @Autowired
//    InventoryCountProductMapper  countProductMapper;
    @Autowired
    AdminDepartmentMapper adminDepartmentMapper;
    @Autowired
    ProcurementMapper procurementMapper;


    @Override
    public Page<WarehouseInout> inoutList(Integer page, Integer limit, Integer inoutType, Integer type, Integer id) {
        Page<WarehouseInout> inoutPage = new Page<>(page, limit);
        Page<WarehouseInout> warehouseInoutPage = inoutMapper.selectInoutPage(inoutPage, inoutType, type, id);
        warehouseInoutPage.getRecords().forEach(warehouseInout -> {
            String operatorName = "";
            String username = "";
            String departName = "";
            if (warehouseInout.getType() == 3){
//                username = adminMapper.selectUsernameById(warehouseInout.getResponsibleId());
//                QueryWrapper<AdminDepartment> wrapper = new QueryWrapper<>();
//                wrapper.lambda().eq(AdminDepartment::getAdminId,warehouseInout.getResponsibleId());
//                AdminDepartment adminDepartment = adminDepartmentMapper.selectOne(wrapper);
//                departName = departmentMapper.selectDepartNameById(adminDepartment.getDepartmentId());
//                if(warehouseInout.getInoutType() == 1){
//                    operatorName = adminMapper.getOutUserName(warehouseInout.getId());
//                }else {
//                    operatorName = adminMapper.getInUserName(warehouseInout.getId());
//                }
            }
            else if (warehouseInout.getType() == 2) {
                //盘点
//                InventoryCountProduct countProduct = countProductMapper.selectById(warehouseInout.getClaimId());
//                operatorName = adminMapper.selectUsernameById(countProduct.getAdminId());
//                username = adminMapper.selectUsernameById(countProduct.getAdminId());
//                departName = departmentMapper.selectDepartNameById(countProduct.getDepartmentId());

            }
            else  if (warehouseInout.getType() == 4){
                Procurement procurement = procurementMapper.selectById(warehouseInout.getClaimId());
                operatorName = adminMapper.selectUsernameById(warehouseInout.getResponsibleId());
                username = adminMapper.selectUsernameById(procurement.getAdminId());
                departName = departmentMapper.selectDepartNameById(procurement.getDepartmentId());
            }
            else {
                //获取经办人名称
//                operatorName = inoutMapper.getOperatorName(warehouseInout.getId());
//                //领用人名称 和部门名称
//                WarehouseClaim warehouseClaim = claimMapper.selectOne(new QueryWrapper<WarehouseClaim>().lambda()
//                        .eq(WarehouseClaim::getId, warehouseInout.getClaimId()));
//                username = adminMapper.selectUsernameById(warehouseClaim.getAdminId());
//                departName = departmentMapper.selectDepartNameById(warehouseClaim.getDepartmentId());
            }
            String warehouseName = warehouseMapper.getWarehouseNameById(warehouseInout.getWarehouseId());
            warehouseInout.setWarehouseName(warehouseName);
            List<InoutProduct> inoutProducts = inoutProductMapper.selectListByInoutId(warehouseInout.getId());
            if (inoutProducts == null){
                inoutProducts = new ArrayList<>();
            }
            warehouseInout.setUserName(username);
            warehouseInout.setDepartmentName(departName);
            warehouseInout.setInoutProductList(inoutProducts);
            warehouseInout.setOperatorName(operatorName);
        });
        return warehouseInoutPage;
    }


    @Override
    public void updateInout(WarehouseInout warehouseInout){
        WarehouseInout inout = inoutMapper.selectById(warehouseInout.getId());
        if(inout == null){
            throw new CustomException(ResultCode.DATA_NOT_FOUND);
        }
        List<InoutProduct> inoutProductList = warehouseInout.getInoutProductList();
        if (inoutProductList.size() != 0) {
            inoutProductList.forEach(claimInout -> {
                if (claimInout.getActualNum() != null){
                    claimInout.setFinallyNum(claimInout.getInceptionNum()-claimInout.getActualNum());
                    inoutProductMapper.updateById(claimInout);
                }
            });
        }
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public void confirmInout(Integer id) {
        WarehouseInout warehouseInout = inoutMapper.selectById(id);
        warehouseInout.setIsPassed(1);
        inoutMapper.updateById(warehouseInout);
        Warehouse warehouse = warehouseMapper.selectById(warehouseInout.getWarehouseId());
        if (warehouse == null){
            throw new CustomException(ResultCode.WAREHOUSE_IS_NOT_EXIST);
        }
        if (warehouse.getIsInventory() ==1 ){
            throw new CustomException(ResultCode.WAREHOUSE_IS_INVENTORY);
        }
        LambdaQueryWrapper<InoutProduct> lambda = new QueryWrapper<InoutProduct>().lambda();
        lambda.eq(InoutProduct::getInoutId, warehouseInout.getId());
        List<InoutProduct> inoutProductList = inoutProductMapper.selectList(lambda);
        if (warehouseInout.getInoutType() == 2 && warehouseInout.getType() == 3 || warehouseInout.getType() == 4 && warehouseInout.getInoutType() == 2) {
            for (InoutProduct inoutProduct : inoutProductList) {
                //判断仓库库存有该产品没有
                QueryWrapper<Stock> wrapper = new QueryWrapper<>();
                wrapper.lambda().eq(Stock::getWarehouseId, warehouseInout.getWarehouseId()).eq(Stock::getProductSkuId, inoutProduct.getClaimsProductId());
                Stock stock = stockMapper.selectOne(wrapper);
                if (stock == null) {
                    Stock newStock = new Stock();
                    newStock.setCreateTime(DateUtil.date());
                    newStock.setWarehouseId(warehouseInout.getWarehouseId());
                    newStock.setProductSkuId(inoutProduct.getClaimsProductId());
                    newStock.setUnitId(inoutProduct.getUnitId());
                    newStock.setQuantity(inoutProduct.getActualNum());
                    stockMapper.insert(newStock);
                } else {
                    stock.setQuantity(inoutProduct.getActualNum());
                }
            }
        } else  {
            for (InoutProduct inoutProduct : inoutProductList) {
                QueryWrapper<Stock> wrapper = new QueryWrapper<>();
                wrapper.lambda().eq(Stock::getWarehouseId,warehouseInout.getWarehouseId()).eq(Stock::getProductSkuId,inoutProduct.getClaimsProductId());
                Stock stock = stockMapper.selectOne(wrapper);
                stock.setQuantity(inoutProduct.getFinallyNum());
                stockMapper.updateById(stock);
            }
        }
        //调拨 出库单确认之后才生成入库单
//        if (warehouseInout.getInoutType() == 1 && warehouseInout.getType() == 3){
//            //生成入库单
//            WarehouseInout warehouseIn = new WarehouseInout();
//            QueryWrapper<Allocate> wrapper = new QueryWrapper<>();
//            wrapper.lambda().eq(Allocate::getId,warehouseInout.getClaimId());
//            Allocate allocate = allocateMapper.selectOne(wrapper);
//            warehouseIn.setInoutType(2);
//            warehouseIn.setInoutTime(DateUtil.date());
//
//            //自动生成编号
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
//            String code = "INOUT-" + sdf.format(allocate.getCreateTime());
//            String maxCode =  inoutMapper.maxRoundInoutNumber(code);
//            String newCode = null;
//            if (StrUtil.isEmpty(maxCode)){
//                newCode = code + "01";
//            }
//            else {
//                String getMaxCode = maxCode.substring(14, 16);
//                newCode = code + DateNumUtils.getNum(getMaxCode);
//            }
//            warehouseIn.setInoutCode(newCode);
//            warehouseIn.setType(3);
//            warehouseIn.setClaimId(allocate.getId());
//            warehouseIn.setWarehouseId(allocate.getInWarehouseId());
//            warehouseIn.setResponsibleId(allocate.getInAdminId());
//            inoutMapper.insert(warehouseIn);
//            //入库的物品表
//            LambdaQueryWrapper<AllocateProduct> lambdaWrapper = new QueryWrapper<AllocateProduct>().lambda();
//            lambdaWrapper.eq(AllocateProduct::getAllocateId, allocate.getId());
//            List<AllocateProduct> allocateProducts = allocateProductMapper.selectList(lambdaWrapper);
//            for (AllocateProduct allocateProduct : allocateProducts) {
//                InoutProduct inoutProduct = new InoutProduct();
//                inoutProduct.setInoutId(warehouseIn.getId());
//                inoutProduct.setClaimsProductId(allocateProduct.getProductId());
//                //获取物品原始库存
//                Stock stock = stockMapper.selectOneByWarehouseAndProuctId(allocate.getInWarehouseId(),allocateProduct.getProductId());
//                if (stock == null){
//                    inoutProduct.setInceptionNum(0.00);
//                    Integer unitId = inoutProductMapper.SelectUnitIdByProductId(allocateProduct.getProductId());
//                    inoutProduct.setUnitId(unitId);
//                }else {
//                    inoutProduct.setInceptionNum(stock.getQuantity());
//                    inoutProduct.setUnitId(stock.getUnitId());
//                }
//                inoutProduct.setInoutNum(allocateProduct.getAllocateNum());
//                inoutProductMapper.insert(inoutProduct);
//                if (warehouseIn.getInoutType() == 1){
//                    inoutProduct.setFinallyNum(inoutProduct.getInceptionNum() - allocateProduct.getAllocateNum());
//                } else {
//                    inoutProduct.setFinallyNum(inoutProduct.getInceptionNum() + allocateProduct.getAllocateNum());
//                }
//                inoutProductMapper.updateById(inoutProduct);
//            }
//        }
    }

}
